package icu.twtool.ui.component

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.onClick
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.LocalContentColor
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.pointer.pointerHoverIcon
import androidx.compose.ui.unit.dp
import icu.twtool.ui.router.Route
import icu.twtool.ui.style.MyCursor

/**
 * @author Wen
 * @since 2022-11-02
 */
@Composable
@Suppress("FunctionName")
fun ColumnScope.TabList(tabs: List<Route>, activeTab: Route, onUpdate: (Route) -> Unit) {
    Column(modifier = Modifier.weight(1f).padding(vertical = 16.dp)) {
        for (route in tabs) {
            val active = route == activeTab
            TabItem(route.name, active) {
                if (!active) onUpdate(route)
            }
            Spacer(Modifier.requiredHeight(8.dp))
        }
    }
}

@Composable
@Suppress("FunctionName")
@OptIn(ExperimentalFoundationApi::class)
private fun TabItem(routeName: String, active: Boolean, onClick: () -> Unit) {
    Box(
        Modifier.fillMaxWidth().height(38.dp).onClick(onClick = onClick)
            .pointerHoverIcon(MyCursor.HandCursor)
            .clip(_tabItemShape).run {
                if (active) background(LocalContentColor.current.copy(0.2f))
                else this
            }
    ) {
        if (active) Box(Modifier.clip(_borderShape).width(2.dp).fillMaxHeight().background(LocalContentColor.current))
        Text(text = routeName, modifier = Modifier.align(Alignment.Center))
    }
}

private val _tabItemShape = RoundedCornerShape(0.dp, 4.dp, 4.dp, 0.dp)
private val _borderShape = RoundedCornerShape(0.dp, 2.dp, 2.dp, 0.dp)